/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:44
 */

package com.lenovo.mso2o.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lenovo.framework.base.ActionBarFragmentActivity;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.base.InjectableFragment;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.conf.FConstants;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.util.CompatHelper;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FPreferenceManager;
import com.lenovo.framework.view.overscroll.OverScrollDecoratorHelper;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.biz.AccountManagerImpl;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.BillNumber;
import com.lenovo.mso2o.entity.Shortcut;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.ui.WebActivity;
import com.lenovo.mso2o.ui.adapter.ShortcutAdapter;
import com.lenovo.mso2o.util.ActionCallbacks;
import com.lenovo.mso2o.util.Utils;
import com.trello.rxlifecycle.FragmentEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Scheduler;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class IndexFragment extends InjectableFragment implements ShortcutAdapter.OnShortcutSelectedListener {

    private final String TAG = this.getClass().getName();
    private View rootView;
    private Subscription _subscription;
    private OrderAPI orderAPI;
    private Scheduler.Worker worker;
    private static int times_anim = 1;

    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public IndexFragment() {
        // Required empty public constructor
    }

    @Bind(R.id.shortcuts) RecyclerView mRecyclerView;
    ShortcutAdapter mAdapter;
    List<Shortcut> mainList;
    private int num = 0;
    @Bind(R.id.grab_order_number) TextView grabNumber;
    @Bind(R.id.grab_number) TextView grab;
    @Bind(R.id.receive_order_number) TextView receiveNumber;
    @Bind(R.id.receive_number) TextView receive;
    @Bind(R.id.iv_esupport_logo)
    ImageView ivLogo;
    @Bind(R.id.iv_home_page_bg_up)
    ImageView ivHomepageBg;
    @Bind(R.id.frame_layout_receive_order)
    FrameLayout frameLayoutReceive;
    @Bind(R.id.frame_layout_grab_order)
    FrameLayout frameLayoutGrab;
    @Bind(R.id.relative_layout_grab_and_receive)
    RelativeLayout relaLayoutGrabReci;

    private static int times = 1;
    private void initHomepageBg(){
        ViewGroup.LayoutParams params = ivHomepageBg.getLayoutParams();
        WindowManager wm = this.getActivity().getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        params.height = (int)(0.9*width);
        ivHomepageBg.setLayoutParams(params);
    }


    @OnClick(R.id.main_receive_orders)
    public void onClickMainReceiveOrder(View view){
        Bundle bundle = new Bundle();
        bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.receive_order_pool);
        //bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, OrderReceivingFragment.class.getName());
        bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, OrderReceivingFragment.class.getName());
        bundle.putBoolean(ActionBarFragmentActivity.RIGHT_ACTIONBAR_ENABLE, true);
        bundle.putBoolean(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
        Intent intent = new Intent(getActivity(), ActionBarFragmentActivity.class);
        intent.putExtras(bundle);
        getActivity().startActivityForResult(intent, MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS);
    }

    @OnClick(R.id.main_grab_orders)
    public void onClickMainGrabOrder(View view){
        Intent intent = new Intent(view.getContext(), ActionBarFragmentActivity.class);
        intent.putExtra(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, OrderGrabListFragment.class.getName());
        intent.putExtra(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
        intent.putExtra(MSConstants.FragmentType.FRAGMENT_ORDERTYPE, MSConstants.FragmentType.FRAGMENT_GRABORDERS);
        intent.putExtra(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.grab_activity_title);
        intent.putExtra(ActionBarFragmentActivity.RIGHT_ACTIONBAR_ENABLE, true);
        intent.putExtra(ActionBarFragmentActivity.BACK_REFRESHABLE, true);
        getActivity().startActivityForResult(intent, MSConstants.FragmentType.FRAGMENT_GRABORDERS);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(rootView != null) return rootView;
        // Inflate the layout for this fragment
        View view = super.onCreateView(inflater, container, savedInstanceState);
        // 应该从存储处获取相应的模块的编号
        mainList = new ArrayList<Shortcut>();
        mAdapter = new ShortcutAdapter(this.getActivity());
        //手动设置imageview的宽高
        WindowManager wm = this.getActivity().getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams params = ivLogo.getLayoutParams();
        params.height=width/15;
        params.width =width/3;
        ivLogo.setLayoutParams(params);

        initHomepageBg();
        orderAPI = ServiceGenerator.createService(OrderAPI.class);
        //为recyclerView添加header
        //RecyclerViewHeader header = (RecyclerViewHeader) getActivity().findViewById(R.id.header);

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new GridLayoutManager(this.getContext(), 4));
        if(CompatHelper.hasIceCreamSandwich()){
            OverScrollDecoratorHelper.setUpOverScroll(mRecyclerView, OverScrollDecoratorHelper.ORIENTATION_VERTICAL);
        }
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setList(mainList);
        mAdapter.setOnShortcutSelectedListener(this);
        return rootView = view;
    }

    @Override
    public void onResume() {
        super.onResume();
        /*if (times_anim == 1){
            times_anim = -1;
            ObjectAnimator.ofFloat(relaLayoutGrabReci, "alpha", 0F, 1F).setDuration(500).start();
            ObjectAnimator.ofFloat(ivLogo, "alpha", 0F, 1F).setDuration(500).start();
        }*/
        /*ObjectAnimator.ofFloat(relaLayoutGrabReci, "translationX", 400F, 0).setDuration(1000).start();
        ObjectAnimator.ofFloat(ivLogo, "translationX", 400F, 0).setDuration(1000).start();*/
        refreshShrotcuts();
    }

    @Override
    public void onStop() {
        super.onStop();
        currentItem = 0;
    }

    public int currentItem;

    @Override
    public void onShortcutSelected(Shortcut shortcut, int position) {
        Intent intent;
        if (position <= mainList.size()) {
            switch (mainList.get(position).getId()) {
                case ShortcutSettingFragment.FASTBILLING:
                    intent = new Intent(ContextManager.context(), WebActivity.class);
                    intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, MSConstants.APIConstants.FAST_BILLING_URL);
                    getActivity().startActivity(intent);
                    break;
                case ShortcutSettingFragment.MYMESSAGE:
                    break;
                case ShortcutSettingFragment.ADDFUNCTION:
                    Bundle bundle = new Bundle();
                    bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, ShortcutSettingFragment.class.getName());
                    bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.shortcuts_settings);
                    intent = new Intent(this.getContext(), ActionBarFragmentActivity.class);
                    intent.putExtras(bundle);
                    getActivity().startActivity(intent);
                    break;
            }
        }
    }

    //刷新主界面gridview
    public void refreshShrotcuts() {
        mainList.clear();
        if (FPreferenceManager.getBoolean(AccountManagerImpl.KEY_FASTBILLING, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.FASTBILLING));
        }
        /*
        if (FPreferenceManager.getBoolean(AccountManagerImpl.KEY_FASTBILLING, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.FASTBILLING));
        }
        if (FPreferenceManager.getBoolean(FAccounts.KEY_SCHEME_QUERY, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.SCHEME_QUERY));
        }
        if (FPreferenceManager.getBoolean(FAccounts.KEY_PRODUCTDESCRIPTION, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.PRODUCTDESCRIPTION));
        }
        if (FPreferenceManager.getBoolean(FAccounts.KEY_INITIATECHAT, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.INITIATECHAT));
        }
        if (FPreferenceManager.getBoolean(FAccounts.KEY_HANDYHAVERSACK, false)) {
            mainList.add(new Shortcut(ShortcutSettingFragment.HANDYHAVERSACK));
        }
        */
        mainList.add(new Shortcut(ShortcutSettingFragment.ADDFUNCTION));
        mAdapter.setList(mainList);
    }

    public void refreshOrder(int grab,int receive) {
        DLog.i("tip:", "grab:" + grab + "  receive:" + receive);
        if(this.grabNumber != null)
            if(grab > 0) {
                this.grabNumber.setVisibility(View.VISIBLE);
                this.grabNumber.setText(" " + grab + " ");
                //home_page_order_alert_red_shape_rec
                //home_page_order_alert_red_shape
                if(grab >= 10){
                    this.grabNumber.setBackgroundResource(R.drawable.home_page_order_alert_red_shape_rec);
                }else{
                    this.grabNumber.setBackgroundResource(R.drawable.home_page_order_alert_red_shape);
                }
            } else {
                this.grabNumber.setVisibility(View.INVISIBLE);
            }
        if(this.grab!= null)
            this.grab.setText(" " + grab + " ");
        if(this.receiveNumber!= null)
            if(receive > 0) {
                this.receiveNumber.setVisibility(View.VISIBLE);
                this.receiveNumber.setText(" " + receive + " ");
                if(receive >= 10){
                    this.receiveNumber.setBackgroundResource(R.drawable.home_page_order_alert_red_shape_rec);
                }else{
                    this.receiveNumber.setBackgroundResource(R.drawable.home_page_order_alert_red_shape);
                }
            }
            else {
                this.receiveNumber.setVisibility(View.INVISIBLE);
            }
        if(this.receive!= null)
            this.receive.setText(" " + receive + " ");
    }

    @Override
    public int provideContentRes() {
        return R.layout.index_fragment;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {
        if(worker != null) {
            DLog.w("worker", "unsubscribe");
            worker.unsubscribe();
            worker = null;
        }
        if(_subscription != null){
            _subscription.unsubscribe();
        }
    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {
        if(worker != null) {
            DLog.w("worker", "unsubscribe");
            worker.unsubscribe();
            worker = null;
        }
        worker = Schedulers.newThread().createWorker();
        DLog.w("worker", "schedule");
        if(times == 1) {//保证只显示一次loading
            times = -1;
            ((FBaseActivity) getActivity()).processPreview(null, null, true);
        }

        worker.schedulePeriodically(new Action0() {
            @Override
            public void call() {
                if (_subscription == null || _subscription.isUnsubscribed())
                    _subscription =
                         orderAPI.updateNumber()
                        .compose(IndexFragment.this.<Res<BillNumber>>bindUntilEvent(FragmentEvent.STOP))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())
                        .subscribe(new NetworkObserver<Res<BillNumber>>() {
                            @Override
                            public void onSuccess(final Res<BillNumber> billNumberRes) {
                                ((FBaseActivity)getActivity()).processDismiss();
                                if (billNumberRes.getEcode() == 0)
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            refreshOrder(billNumberRes.getResult().getGrabqty(), billNumberRes.getResult().getAcceptqty());
                                        }
                                    });
                                else onFailure(billNumberRes.getMessage());
                            }

                            @Override
                            public void onFailure(String tip) {
                                ((FBaseActivity)getActivity()).processDismiss();
                                DLog.toast(tip);
                            }
                        });
            }
        }, 0, 3, TimeUnit.SECONDS);
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView ();
        if(worker != null) {
            worker.unsubscribe();
            worker = null;
        }
        if (rootView != null) {
            ((ViewGroup)rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
